<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>


    <script>

        ajax({
            path : 'http://192.168.58.110/php/ajax.php' ,
            type : 'POST' ,
            success : res => {
                console.log(res);
            }
        })

        ajax({
            path : 'http://192.168.58.110/php/get.php' ,
            type : 'GET' ,
            data : {
                username : 'q' ,
                password : '1222'
            },
            success : res => {
                console.log(res);
            }
        })


        function ajax(options) {

            // 默认值
            const {
                path ,
                type ,
                data = {} ,
                success
            } = options ;
            // 处理参数
            let params = '';
            for (let key in data) {
                params += `${key}=${data[key]}&`;
            }
            // 最后会一个&
            params = params.substring(0, params.length - 1);


            const xhr = new XMLHttpRequest();

            // 判断请求的方式   传参时不分大小写
            if (type.toLowerCase() === 'get') {
                xhr.open('get', path + '?' + params, true);
                xhr.send();
            }
            else if (type.toLowerCase() === 'post') {
                xhr.open('post', path, true);
                // 设置请求头
                xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
                // key=value&key=value
                xhr.send(params);
            }

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    const res = xhr.responseText;
                    success(res);
                }
            }
        }

    </script>

</body>

</html>